#!/usr/bin/perl

use strict;
use FindBin qw($Bin);
use Getopt::Long;

sub usage {
    die "Usage: dev-appengine [--wipe] [-a] [-p port] -- [other_dev_appserver_opts]";
}

my $opt_wipe;
my $opt_port;
my $opt_all;  # listen on all interfaces
GetOptions("wipe" => \$opt_wipe,
           "all" => \$opt_all,
           "p=i" => \$opt_port,
           ) or usage();

my $sdk = readlink("$Bin/appengine-sdk")
    or die "No App Engine SDK symlink; please:\n  \$ ln -s /path/to/appengine-go-sdk $Bin/appengine-sdk\n\n";

my @args = (
    "$sdk/dev_appserver.py",
    "--skip_sdk_update_check",
    );

if ($opt_all) {
    push @args, "-a", "0.0.0.0";
}
if ($opt_wipe) {
    push @args, "--clear_datastore";
}
if ($opt_port) {
    push @args, "--port", "$opt_port";
} else {
    push @args, "--port", "3179";
}
push @args, @ARGV;

chdir "$Bin/server/appengine" or die "$!";

my $sourceRoot = "$Bin/server/appengine/source_root";
# import in the appengine dir all the static files, so they get uploaded
# TODO(mpl): do a smarter mirroring when we convert this to go
unless (-d $sourceRoot) {
  # copy ui files
  system("mkdir", "-p", $sourceRoot) and die "Failed to create $sourceRoot.\n";
  my $dest = "$sourceRoot/server/camlistored";
  system("mkdir", "-p", $dest) and die "Failed to create uiDir.\n";
  system("cp", "-a", "$Bin/server/camlistored/ui", $dest) and die "Failed to cp uiDir.\n";
  # copy closure files
  $dest = "$sourceRoot/third_party/closure/lib";
  system("mkdir", "-p", $dest) and die "Failed to create closureDir.\n";
  system("cp", "-a", "$Bin/third_party/closure/lib/closure", $dest) and die "Failed to cp uiDir.\n";
  # copy favicon.ico
  $dest = "$sourceRoot/pkg/server";
  system("mkdir", "-p", $dest) and die "Failed to create pkg/server.\n";
  system("cp", "$Bin/pkg/server/favicon.ico", $dest) and die "Failed to cp favicon.ico.\n";
}

push @args, ".";
print "\$ @args\n";

exec(@args);
